<template>
    <div>
         <el-row style="margin-bottom:20px;">
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item>新闻动态</el-breadcrumb-item>
                <el-breadcrumb-item v-if="showPage==1">新闻列表</el-breadcrumb-item>
                <el-breadcrumb-item v-if="showPage==2">新增新闻</el-breadcrumb-item>
                <el-breadcrumb-item v-if="showPage==3">修改新闻</el-breadcrumb-item>
                <el-breadcrumb-item v-if="showPage==4">新闻预览</el-breadcrumb-item>
                <el-breadcrumb-item v-if="showPage==4">{{previewForm.title}}</el-breadcrumb-item>
            </el-breadcrumb>
        </el-row>

        <!--新闻列表-->
        <el-row v-show='showPage==1'>
            <!--按钮+搜索-->
            <el-row :gutter="10">
                <el-col :span='3'>
                    <el-button type="primary" size="small" @click='addNews'>新增新闻</el-button>
                </el-col>
                <el-col :span='3' :offset="1">
                    <el-input size="small" placeholder="请输入标题" style='width:100%' suffix-icon="el-icon-search" :clearable='true' @clear="cleanKey" v-model="table.title" @keyup.enter.native="queryKey"></el-input>
                </el-col>

                <el-col :span="3">
                    <el-select v-model.number="table.type" clearable placeholder="新闻类型" size='small' @change='newsTypeChange'>
                        <el-option v-for="item in table.newsTypeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-col>

                <el-col :span="3">
                    <el-select v-model.number="table.state" clearable placeholder="新闻状态" size='small' @change='newsStateChange'>
                        <el-option v-for="item in table.newsStateList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-col>
            </el-row>

            <!--表格-->
            <el-row style="margin-top:10px">
                <el-table :data='table.tableData' border stripe style="width:100%" size="small" :highlight-current-row="true" ref="multipleTable">
                    <el-table-column label="编号" prop='newsId' min-width="150"></el-table-column>
                    <el-table-column label="标题" prop='title' min-width="250"></el-table-column>
                    <el-table-column label='首页排序' min-width="120">
                        <template slot-scope="scope" prop='logicOrder'>
                            <el-tag type="danger" v-if='scope.row.logicOrder==1||scope.row.logicOrder==2'>首页{{scope.row.logicOrder}}</el-tag>
                            <el-tag type="success" v-if='scope.row.logicOrder>2'>首页{{scope.row.logicOrder}}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="类型" min-width="120">
                        <template slot-scope="scope">
                            <span v-if='scope.row.type==1'>高招资讯</span>
                            <span v-if='scope.row.type==2'>报考资讯</span>
                        </template>
                    </el-table-column>
                    <el-table-column label='序号' prop='orderNum' min-width="120"></el-table-column>
                    <el-table-column label="状态" min-width="120">
                        <template slot-scope="scope">
                            <el-tag type="info" v-if='scope.row.state==0'>未发布</el-tag>
                            <el-tag type="success" v-if='scope.row.state==1'>已发布</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="创建时间" prop='createTime' min-width="120"></el-table-column>
                    <el-table-column label="发布时间" prop='publishTime' min-width="120"></el-table-column>
                    <el-table-column label='操作' min-width='200'>
                        <template slot-scope="scope">
                            <el-button type="text" v-if='scope.row.state==0' @click="toPublish(scope.row)">发布</el-button>
                            <el-button type="text" v-if='scope.row.state==0' @click="toModify(scope.row)">修改</el-button>
                            <el-button type="text" v-if='scope.row.state==0' @click="toDelete(scope.row)">删除</el-button>

                            <el-button type="text" v-if='scope.row.state==1' @click="toCancel(scope.row)">取消发布</el-button>
                            <el-button type="text" @click="toPreview(scope.row)">预览</el-button>
                            
                            <el-dropdown @command="logicOrderCommand" v-if='scope.row.state==1'>
                                <span class="el-dropdown-link">
                                    修改序号<i class="el-icon-arrow-down el-icon--right"></i>
                                </span>
                                <el-dropdown-menu slot="dropdown">
                                    <template v-for="item in orderNumButtonList">
                                        <el-dropdown-item :key="item.command" disabled 
                                        v-if='item.logicOrder == scope.row.orderNum'>{{item.value}}</el-dropdown-item>
                                        <el-dropdown-item :key="item.command" :command='beforeLogicCommand(scope.row, item.command)'
                                        v-if='item.logicOrder != scope.row.orderNum'>{{item.value}}</el-dropdown-item>
                                    </template>
                                </el-dropdown-menu>
                            </el-dropdown>
                        </template>
                        
                    </el-table-column>
                </el-table>
                <!--分页条-->
                 <el-pagination style="margin-top:10px;" @current-change="currentChangeHandle" :current-page="table.currentPage"
                :page-size="table.pageSize" layout="total, prev, pager, next, jumper" :total="table.rowCount"></el-pagination>
            </el-row>
        </el-row>

        <!--新增新闻-->
        <el-row v-show='showPage==2 || showPage==3'>
            <el-row>
                <el-col :span='3'>
                    <el-button type="primary" size="small" @click='addBack'>返回列表</el-button>
                </el-col>
            </el-row>
            <el-form style="margin-top:10px;" label-position='right' label-width='80px' :model='addForm'
            ref='addForm' size='small' :rules='addForm.rules'>
                <el-form-item label="标题" prop='title'>
                    <el-input style="width:500px;" v-model="addForm.title" placeholder="请输入标题"></el-input>
                </el-form-item>
                <el-form-item label="摘要" prop="summary">
                    <el-input style="width:500px;" type="textarea" :rows="3" placeholder="请输入摘要内容" v-model="addForm.summary"/>
                </el-form-item>
                <el-form-item label="类型" prop="type">
                    <el-select v-model.number="addForm.type" placeholder="请选择类型" size='small' style="width:200px;">
                        <el-option v-for='item in table.newsTypeList' :key='item.value' :label='item.label' :value='item.value'></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="排序号" prop='orderNum'>
                    <el-input-number style="width:200px;" v-model="addForm.orderNum" :min="1" :max="100" :precision="0"></el-input-number>
                </el-form-item>
                <el-form-item label='发布时间' prop="publishTime">
                        <el-date-picker style="width:200px;" 
                        v-model="addForm.publishTime" type="datetime" placeholder="选择日期时间" 
                        :editable='false' value-format='yyyy-MM-dd HH:mm:ss' format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
                </el-form-item>
                <el-form-item label='正文' prop='content'>
                    <el-row>
                        <el-col :span='12'>
                            <vue-ueditor-wrap v-model="addForm.content" :config="addForm.editorConfig"/>
                        </el-col>
                        <!-- <el-col :span='12'>
                            <div class='news-view' v-html="addForm.content"/>
                        </el-col> -->
                    </el-row>
                    
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm('addForm')">保存</el-button>
                </el-form-item>
            </el-form>
        </el-row>
    </div>
</template>

<script>
import VueUeditorWrap from 'vue-ueditor-wrap'
import conf from '@/utils/conf.js'
var moment = require('moment');

export default {
    data(){
        return {
            showPage: 1,
            headers: {
                Authorization: sessionStorage.token
            },
            orderNumButtonList: [
                {command: 1, value:'首页1', logicOrder: 1},
                {command: 2, value:'首页2', logicOrder: 2},
                {command: 3, value:'首页3', logicOrder: 3},
                {command: 4, value:'首页4', logicOrder: 4},
                {command: 5, value:'首页5', logicOrder: 5},
                {command: 6, value:'首页6', logicOrder: 6},
                {command: 7, value:'首页7', logicOrder: 7},
            ],
            table: {
                tableData: [],
                currentPage: 1,
                pageSize: 10,
                rowCount: 0,
                title: '',
                state: '',
                type: '',
                newsStateList: [
                    {label:"未发布",value:0},
                    {label:"已发布",value:1},
                ],
                newsTypeList: [
                    {label:"高招资讯",value:1},
                    {label:"报考资讯",value:2}
                ]
            },
            addForm: {
                isCreate: true,
                newsId: '',
                title: '',
                summary: '',
                orderNum: 0,
                type: '',
                publishTime: '',
                content: '',
                editorConfig: {
                    // 编辑器自动被内容撑高
                    autoHeightEnabled: true,
                    // 初始容器高度
                    initialFrameHeight: 450,
                    // 初始容器宽度
                    initialFrameWidth: '685',
                    // 上传文件接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！）
                    // serverUrl: 'http://35.201.165.105:8000/controller.php',
                    serverUrl: conf.baseUrl() + '/UEditor',
                    // UEditor 资源文件的存放路径，如果你使用的是 vue-cli 生成的项目，通常不需要设置该选项，vue-ueditor-wrap 会自动处理常见的情况，如果需要特殊配置，参考下方的常见问题2
                    UEDITOR_HOME_URL: conf.ueditorConf()
                },
                rules: {
                    title: [
                        {required: true, message: '请填写标题', trigger: 'blur'}
                    ],
                    summary: [
                        {required: true, message: '请填写摘要', trigger: 'blur'},
                        {min: 20, max: 100, message: '摘要长度为20-100'}
                    ],
                    // imgUrl: [
                    //     {required: true, message: '请添加新闻图片', trigger: 'blur'}
                    // ],
                    type: [
                        {
                            required: true,
                            message: '请选择类型',
                            trigger: 'blur,change',
                            type: 'number'
                        }
                    ],
                    content: [
                        {required: true, message: '请填写正文', trigger: 'blur'}
                    ],
                    publishTime: [
                        {required: true, message: '请选择发布时间', trigger: 'blur,change'}
                    ]
                },

            },

        }
    },
    components: {
        VueUeditorWrap
    },

    methods: {

        //预览
        toPreview(row){
            let url = conf.baseUrl() + '/news/' + row.newsId;
            window.open(url, '_blank');
        },

        logicOrderCommand(command){

            let msg = '确定序号由' + command.row.orderNum + '修改为'+command.command + '吗?';
            this.$confirm(msg, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                })
            .then(() => {
                let p = {};
                let url = '/api/news/commandOrderNum';
                p.newsId = command.row.newsId;
                p.orderNum = command.command;
                return this.$http.fetch(url, p)
            })
            .then(()=>{
                this.getTableData();
            })
            .catch(()=>{

            })
        },

        beforeLogicCommand(row, command){
            return {
                'row': row,
                'command': command
            }
        },

        getTableData(){
            let p = {};
            let url = '/api/news/list';
            p.start = (this.table.currentPage - 1) * this.table.pageSize;
            p.num = this.table.pageSize;
            p.title = this.table.title;
            p.state = this.table.state;
            p.type = this.table.type;
            this.$http.fetch(url, p)
                .then(res => {
                    this.table.tableData = res.data.rows;
                    this.table.rowCount = res.data.total;
                })
        },
        cleanKey(){
            this.table.currentPage = 1;
            this.table.queryKey = '';
            this.getTableData();
        },
        queryKey(){
            this.table.currentPage = 1;
            this.getTableData();
        },
        newsStateChange(value){
            this.table.state = value;
            this.table.currentPage = 1;
            this.getTableData();
        },
        newsTypeChange(value){
            this.table.type = value;
            this.table.currentPage = 1;
            this.getTableData();
        },


        //翻页
        currentChangeHandle(currentPage) {
            this.table.currentPage = currentPage;
            this.getTableData();
        },

        addNews(){
            this.addForm.title = '';
            this.addForm.summary = '';
            this.addForm.orderNum = 100;
            this.addForm.type = '';
            this.addForm.content = '';
            this.addForm.publishTime = '';
            this.$refs['addForm'].clearValidate();
            this.addForm.isCreate = true;
            this.showPage = 2;
        },

        toModify(row){
            let p = {};
            let url = '/api/news/get';
            p.newsId = row.newsId;

            let time = moment(row.publishTime);
            let ll = time.valueOf();
            let dd = new Date(ll);

            this.$http.fetch(url, p)
            .then(res=>{
                this.addForm.newsId = res.data.newsId;
                this.addForm.title = res.data.title;
                this.addForm.summary = res.data.summary;
                this.addForm.orderNum = res.data.orderNum;
                this.addForm.type = res.data.type;
                this.addForm.publishTime = dd;
                this.addForm.content = res.data.content;

                this.$refs['addForm'].clearValidate();
                this.addForm.isCreate = false;
                this.showPage = 3;
            })
        },


        addBack(){
            this.showPage = 1;
        },

        submitForm(formName){
            this.$refs[formName].validate((valid) => {
                if(valid){
                    let p = {};
                    let url = '';
                    if(!this.addForm.isCreate){
                        p.newsId = this.addForm.newsId;
                        url = '/api/news/modify';
                    }else{
                        url = '/api/news/add';
                    }
                    p.title = this.addForm.title;
                    p.summary = this.addForm.summary;
                    p.orderNum = this.addForm.orderNum;
                    p.type = this.addForm.type;
                    p.content = this.addForm.content;
                    console.log(this.addForm.publishTime)
                    let publishTime = this.addForm.publishTime;
                    if(publishTime){
                        let time = moment(publishTime).format("YYYY-MM-DD HH:mm:ss");
                        console.log(time)
                        p.publishTime = time;
                    }
                    
                    this.$http.fetch(url, p)
                    .then(res=>{
                        this.getTableData();
                        this.showPage = 1;
                    })
                }
            });
        },

        //发布
        toPublish(row){
            this.$confirm('确定发布吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                })
            .then(() => {
                let p = {};
                let url = '/api/news/publish';
                p.newsId = row.newsId
                return this.$http.fetch(url, p)
            })
            .then(()=>{
                this.getTableData();
            })
            .catch(()=>{

            })
        },

        //取消发布
        toCancel(row){
            this.$confirm('确定取消发布吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                })
            .then(() => {
                let p = {};
                let url = '/api/news/cancel';
                p.newsId = row.newsId
                return this.$http.fetch(url, p)
            })
            .then(()=>{
                this.getTableData();
            })
            .catch(()=>{

            })
        },

        //删除新闻
        toDelete(row){
            this.$confirm('确定删除吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                })
            .then(() => {
                let p = {};
                let url = '/api/news/delete';
                p.newsId = row.newsId
                return this.$http.fetch(url, p)
            })
            .then(()=>{
                this.getTableData();
            })
            .catch(()=>{

            })
        },

    },

    mounted(){
        this.getTableData();
    }

}
</script>

<style scoped>
.preview-div{
    width: 1000px;
    background-color: #ffffff;
    margin-top:10px;
}

.news-view {
    width: 669px;
    min-height: 500px;
    border: 1px solid #000000;
    background-color: #ffffff;
}
.news-view img {
    max-width: 100%;
}
.news-view table {
    border:1px solid #ffffff;
}

.el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
    margin-left: 10px;
}

.el-icon-arrow-down {
    font-size: 12px;
}
</style>